package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.AccountMapper;
import com.example.dao.OrderMapper;
import com.example.dto.StorageDTO;
import com.example.entity.Order;
import com.example.feign.StorageFeignClient;
import com.example.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private StorageFeignClient storageFeignClient;



    @Override
    @GlobalTransactional
    public void purchase(String userId, String commodityCode, int orderCount, int money) throws Exception {
        try {
            // 新增订单
            baseMapper.updateOrder(userId, commodityCode, orderCount, money);

            // 减库存
            StorageDTO storageDTO = new StorageDTO();
            storageDTO.setCommodityCode(commodityCode);
            storageDTO.setCount(orderCount);
            storageFeignClient.updateStorage(storageDTO);

            // 故意引发异常用于测试
            int a = 1 / 0;
            System.out.println(a);

            // 减金额
            accountMapper.updateMoney(userId, money);
        } catch (Exception e) {
            // 手动抛出异常以触发事务回滚
            throw new RuntimeException("回滚 Transaction failed, rolling back...", e);
        }
    }
}
